//
//  RemoteService.m
//  Finder
//
//  Created by cdm on 11-4-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//


#import "RemoteService.h"
#import "ASIFormDataRequest.h"

static RemoteService *instance; 

#pragma mark - Login result xml parser

@interface LoginResutlXMLParser : NSObject <NSXMLParserDelegate> {
    
}

@property (nonatomic, assign) int depth;
@property (nonatomic, assign) BOOL isStartElement;
@property (nonatomic, retain) NSString *currentElement;

@property (nonatomic, assign) int status;
@property (nonatomic, retain) NSString *sessionID;

- (void)parse:(NSString *)xml;

@end

@implementation LoginResutlXMLParser

@synthesize depth;
@synthesize isStartElement;
@synthesize currentElement;

@synthesize status;
@synthesize sessionID;

- (void)dealloc
{
    [self.currentElement release];
    [self.sessionID release];
    
    [super dealloc];
}

- (void)parse:(NSString *)xml
{
    NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    
    [xmlParser parse];
    [xmlParser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    self.isStartElement = YES;
    self.depth++;
    self.currentElement = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    self.isStartElement = NO;
    self.depth--;
    self.currentElement = nil;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (!self.isStartElement) {
        return;
    }
    
    if (self.depth == 2) {
        if ([self.currentElement isEqualToString:@"session-id"]) {
            self.sessionID = string;
        }
    } else if (self.depth == 3) {
        if ([self.currentElement isEqualToString:@"status"]) {
            self.status = [string intValue];
        }
    }
    
}

@end

#pragma mark - Register new user xml parser

@interface RegisterNewUserXMLParser : NSObject <NSXMLParserDelegate> {

}

@property (nonatomic, assign) int depth;
@property (nonatomic, assign) BOOL isStartElement;
@property (nonatomic, retain) NSString *currentElement;

@property (nonatomic, assign) int status;
    
- (void)parse:(NSString *)xml;

@end

@implementation RegisterNewUserXMLParser

@synthesize depth;
@synthesize isStartElement;
@synthesize currentElement;

@synthesize status;

- (void)dealloc
{
    [self.currentElement release];
    
    [super dealloc];
}

- (void)parse:(NSString *)xml
{
    NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    
    [xmlParser parse];
    [xmlParser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    self.isStartElement = YES;
    self.depth++;
    self.currentElement = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    self.isStartElement = NO;
    self.depth--;
    self.currentElement = nil;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (!self.isStartElement) {
        return;
    }
    
    if (self.depth == 3) {
        if ([self.currentElement isEqualToString:@"status"]) {
            self.status = [string intValue];
        }
    }
    
}

@end

#pragma mark - Send email xml parser

@interface SendEmailXMLParser : NSObject <NSXMLParserDelegate> {
    
}

@property (nonatomic, assign) int depth;
@property (nonatomic, assign) BOOL isStartElement;
@property (nonatomic, retain) NSString *currentElement;

@property (nonatomic, assign) int status;

- (void)parse:(NSString *)xml;

@end

@implementation SendEmailXMLParser

@synthesize depth;
@synthesize isStartElement;
@synthesize currentElement;

@synthesize status;

- (void)dealloc
{
    [self.currentElement release];
    
    [super dealloc];
}

- (void)parse:(NSString *)xml
{
    NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    
    [xmlParser parse];
    [xmlParser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    self.isStartElement = YES;
    self.depth++;
    self.currentElement = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    self.isStartElement = NO;
    self.depth--;
    self.currentElement = nil;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (!self.isStartElement) {
        return;
    }
    
    if (self.depth == 3) {
        if ([self.currentElement isEqualToString:@"status"]) {
            self.status = [string intValue];
        }
    }
    
}

@end


#pragma mark - Remote service

@interface RemoteService ()

- (NSString *) encryptPasswordWithMd5: (NSString *) _password;

@end

@implementation RemoteService

+ (RemoteService *)sharedService
{
    @synchronized(self)
	{
		if  (instance  ==  nil)
		{
            instance = [[self alloc] init];
        }
    }
	
	return  instance;
}

+ (id)allocWithZone:(NSZone *)zone 
{
    @synchronized(self) {
        if (instance == nil) {
            instance= [super allocWithZone:zone];
            return instance;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)init {
    self = [super init];
	if (self) {
        
    }
	
	return self;
}

- (void)dealloc 
{
	[super dealloc];
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain 
{
    return self;
}

- (unsigned)retainCount 
{
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release 
{
    //do nothing
}

- (id)autorelease 
{
    return self;
}


- (NSString *)getSessionID
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *uid = device.uniqueIdentifier;
    //NSString *uid = @"7b0d16ab05b0946f97c3e05a9689c535890b625f";
    
	NSString *locale = [[NSLocale currentLocale]localeIdentifier];	
	NSString *model = @"iPhone"; 
	NSString *ver = @"1.0";
    NSString *productName = @"Searching House";
    NSLog(@"uid::%@",uid);
	NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
	[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
	NSDate *date=[NSDate date];
	NSString *time = [dateFormatter stringFromDate:date];
    NSString *passwordString = [NSString stringWithFormat:@"%@_%@_%@_%@",productName,@"2",uid,time];
	NSString *md5password = [self encryptPasswordWithMd5:passwordString];
	NSLog(@"%@",md5password);
    
    NSMutableString *dataStr = [[NSMutableString alloc] init];
    [dataStr appendString:@"<request-login version=\"1.0\">"];
    [dataStr appendString:[NSString stringWithFormat:@"<product_ver>%@</product_ver>",ver]];
    [dataStr appendString:[NSString stringWithFormat:@"<product>%@</product>",productName]];
    [dataStr appendString:[NSString stringWithFormat:@"<locale>%@</locale>",locale]];
    [dataStr appendString:[NSString stringWithFormat:@"<login-type>%@</login-type>",@"2"]];
    [dataStr appendString:[NSString stringWithFormat:@"<login-id>%@</login-id>",uid]];
    [dataStr appendString:[NSString stringWithFormat:@"<udid>%@</udid>",uid]];
    [dataStr appendString:@"<msisdn></msisdn>"];
    [dataStr appendString:@"<smsc></smsc>"];
    [dataStr appendString:[NSString stringWithFormat:@"<ua>%@</ua>",model]];
    [dataStr appendString:[NSString stringWithFormat:@"<time-stamp>%@</time-stamp>",time]];
    [dataStr appendString:[NSString stringWithFormat:@"<password>%@</password>",md5password]];
    [dataStr appendString:@"<session-cs>100</session-cs>"];
    [dataStr appendString:@"</request-login>"];
    
    NSLog(@"Get session id param: %@", dataStr);
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    [paramData appendData:[dataStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    NSString *url= [NSString stringWithFormat:@"http://210.192.96.37:8001/bwrspcore/front.do?action=entrance"];	
    
	ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[request setPostBody:paramData];
	[request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request setTimeOutSeconds:20];
    [request startSynchronous];
    
    NSLog(@"Get session id response code %d", [request responseStatusCode]);
    NSLog(@"Get session id response string %@", [request responseString]);
    NSString *xml = [request responseString];
    
    [request release];
    
    LoginResutlXMLParser *parser = [[LoginResutlXMLParser alloc] init];
    [parser parse:xml];
    NSString *sessionID =[NSString stringWithFormat:@"%@",parser.sessionID];
    NSLog(@"parser.sessionID::%@",parser.sessionID);
    [parser release];
    
    [paramData release];
    [dataStr release];
    return sessionID;
}

- (BOOL)registerNewsUser:(NSString *)phone email:(NSString *)email
{
    NSString *sessionID = [self getSessionID];
    NSLog(@"sessionID::%@",sessionID);
    NSMutableString *dataStr = [[NSMutableString alloc] init];
    [dataStr appendString:@"<request-register version=\"1.0\">"];
    [dataStr appendString:[NSString stringWithFormat:@"<session-id>%@</session-id>", sessionID]];
    [dataStr appendString:[NSString stringWithFormat:@"<ms>%@</ms>", phone]];
    [dataStr appendString:[NSString stringWithFormat:@"<email>%@</email>", email]];
    [dataStr appendString:@"<name></name>"];
    [dataStr appendString:@"<sex></sex>"];
    [dataStr appendString:@"<age></age>"];
    [dataStr appendString:@"<push-token></push-token>"];
    [dataStr appendString:@"</request-register>"];
    
    NSLog(@"Register new user param: %@", dataStr);
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    [paramData appendData:[dataStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *url= [NSString stringWithFormat:@"http://210.192.96.37:8001/bwrspcore/front.do?action=entrance"];	
    
	ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[request setPostBody:paramData];
	[request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request setTimeOutSeconds:20];
    [request startSynchronous];
    
    NSLog(@"Register new user response code %d", [request responseStatusCode]);
    NSLog(@"Register new user response string %@", [request responseString]);
    
    NSString *xml = [request responseString];
    
    if (xml == nil) {
        return NO;
    }
    
    RegisterNewUserXMLParser *parser = [[RegisterNewUserXMLParser alloc] init];
    [parser parse:xml];
    int status = parser.status;

    [parser release];
    [request release];
    [paramData release];
    [dataStr release];

    if (status == 0) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)sendEmail:(NSString *)feedbackEmail content:(NSString *)content
{
    NSString *sessionID = [self getSessionID];
    
    NSMutableString *dataStr = [[NSMutableString alloc] init];
    [dataStr appendString:@"<request-email version=\"1.2\">"];
    [dataStr appendString:[NSString stringWithFormat:@"<session-id>%@</session-id>", sessionID]];
    [dataStr appendString:@"<email-item type=\"1\">"];
    [dataStr appendString:@"<parameters name=\"title\">iPhone用户意见反馈</parameters>"];
    [dataStr appendString:[NSString stringWithFormat:@"<parameters name=\"msg\">%@</parameters>", content]];
    [dataStr appendString:[NSString stringWithFormat:@"<parameters name=\"email\">%@</parameters>", feedbackEmail]];
    [dataStr appendString:@"</email-item>"];
    [dataStr appendString:@"</request-email>"];
    
    NSLog(@"Send email param: %@", dataStr);
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    [paramData appendData:[dataStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *url= [NSString stringWithFormat:@"http://210.192.96.37:8001/bwrspcore/front.do?action=entrance"];	
    
	ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[request setPostBody:paramData];
	[request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request setTimeOutSeconds:20];
    [request startSynchronous];
    
    NSLog(@"Send email response code %d", [request responseStatusCode]);
    NSLog(@"Send email response string %@", [request responseString]);
    
    NSString *xml = [request responseString];
    if (xml == nil) {
        return NO;
    }
    
    SendEmailXMLParser *parser = [[SendEmailXMLParser alloc] init];
    [parser parse:xml];
    int status = parser.status;
    
    [parser release];
    [request release];
    [paramData release];
    [dataStr release];
    
    if (status == 0) {
        return YES;
    } else {
        return NO;
    }
}

- (NSString *) encryptPasswordWithMd5: (NSString *) _password 
{ 
    const char * cStr = [_password UTF8String]; 
    
    unsigned char result[32]; 
    
    CC_MD5(cStr, strlen(cStr), result); 
    
    return [NSString 
            
            stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", 
            
            result[0], result[1], 
            
            result[2], result[3], 
            
            result[4], result[5], 
            
            result[6], result[7], 
            
            result[8], result[9], 
            
            result[10], result[11], 
            
            result[12], result[13], 
            
            result[14], result[15] 
            
            ]; 
} 

@end




